/* -----------------
* brief
* 1. this is code gen by tools
 */

package service

import (
	"fmt"
	"github.com/aliyun/aliyun-oss-go-sdk/oss"
	"github.com/aliyun/aliyun-sts-go-sdk/sts"
	"github.com/mjiulee/lego"
	"github.com/satori/go.uuid"
	"github.com/valyala/fasthttp"
	"os"
	"path"
	"saas_sys_base/modules/oss/service/alioss"
	"saas_sys_base/sysconfig"
)

type AliOssService struct {
	// add your model here

}

var (
	_EndpointName = sysconfig.Config.Aliyun_Oss.Endpoint
	_AK_Id        = sysconfig.Config.Aliyun_Oss.Key_Id
	_KeySecret    = sysconfig.Config.Aliyun_Oss.Endpoint
)

var (
	_stsClient *sts.Client
	_ossClient *oss.Client
	_alioss    *alioss.AliOss
)

func init() {
	_stsClient = NewStsClient()
	_ossClient = NewOssClient()
	_alioss = alioss.NewAliOss()
}

func (t *AliOssService) xxx2() {

}
func NewOssClient() *oss.Client {
	// 用户拿到STS临时凭证后，通过其中的安全令牌（SecurityToken）和临时访问密钥（AccessKeyId和AccessKeySecret）生成OSSClient。
	// 创建OSSClient实例。
	client, err := oss.New(_EndpointName, _AK_Id, _KeySecret, oss.SecurityToken("<yourSecurityToken>"))
	if err != nil {
		fmt.Println("Error:", err)

		// OSS操作。
	}
	return client
}

func NewStsClient() *sts.Client {
	client := sts.NewClient(_AK_Id, _KeySecret, "xxx", "xxx")
	return client
}

func (t *AliOssService) UploadAliOss(file *os.File) {
	inputFileName := file.Name()

	//2. 上传到oss服务器

	endpoint := sysconfig.Config.Aliyun_Oss.Endpoint
	accessKeyId := sysconfig.Config.Aliyun_Oss.Key_Id
	accessKeySecret := sysconfig.Config.Aliyun_Oss.Key_Secret
	bucketName := sysconfig.Config.Aliyun_Oss.Bucket
	objectName := GenerateUploadFileName(inputFileName)
	// 创建OSSClient实例。
	client, err := oss.New(endpoint, accessKeyId, accessKeySecret)
	if err != nil {
		lego.LogError(err)
		return
	}

	// 获取存储空间。
	bucket, err := client.Bucket(bucketName)
	if err != nil {
		lego.LogError(err)
		return
	}
	// 上传文件。
	err = bucket.PutObject(objectName, file)
	if err != nil {
		lego.LogError(err)
		return
	}

}

/*func (t *AliOssService) DownloadAliOss(url string) file *os.File{

}*/

func GenerateUploadFileName(inputFileName string) (newFileName string) {
	prjname := sysconfig.Config.Code.Prjname
	fileExt := path.Ext(inputFileName)
	fileName := inputFileName + "_" + uuid.NewV4().String()

	newFileName = prjname + "/upload/" + fileName + "." + fileExt
	return newFileName
}

func (t *AliOssService) GetPolicyTokenHandler(ctx *fasthttp.RequestCtx) {
	_alioss.GetPolicyTokenHandler(ctx)
}

func (t *AliOssService) OssCallbackhandler(ctx *fasthttp.RequestCtx) {
	_alioss.OssCallbackhandler(ctx)
}
